﻿using System.Security.Cryptography;
using System.Text;

namespace Microsoft.Extensions;

/// <summary>
/// 常用扩展
/// </summary>
public static class MD5Extensions
{
    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="txt"></param>
    /// <param name="length"></param>
    /// <returns></returns>
    public static string Md5Encryption(this string txt, MD5Length length = MD5Length.Length32)
    {
        byte[] sor = Encoding.UTF8.GetBytes(txt);
        MD5 md5 = MD5.Create();
        byte[] result = md5.ComputeHash(sor);
        var strbul = new StringBuilder(40);
        for (int i = 0; i < result.Length; i++)
        {
            //加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
            var xStr = string.Empty;
            switch (length)
            {
                case MD5Length.Length32:
                    xStr = "x2";
                    break;
                case MD5Length.Length48:
                    xStr = "x3";
                    break;
                case MD5Length.Length64:
                    xStr = "x4";
                    break;
            }
            strbul.Append(result[i].ToString(xStr));
        }
        return strbul.ToString().ToUpper();
    }

    public static string PwdEncryption(this string password, string account)
    {
        return $"{password}kaspwd{account}".Md5Encryption();
    }
}

public enum MD5Length
{
    Length32,
    Length48,
    Length64
}
